package com.chance.cc.crawler.prod.command.job.domain.commerce.amazon.realtime;

import com.alibaba.fastjson.JSON;
import com.chance.cc.crawler.core.CrawlerEnum;
import com.chance.cc.crawler.core.CrawlerJob;
import com.chance.cc.crawler.core.downloader.HttpConfig;
import com.chance.cc.crawler.core.downloader.HttpPage;
import com.chance.cc.crawler.core.filter.FilterUtils;
import com.chance.cc.crawler.core.queue.crawler.CrawlerQueueConfig;
import com.chance.cc.crawler.core.record.CrawlerRecord;
import com.chance.cc.crawler.core.record.CrawlerRequestRecord;
import com.chance.cc.crawler.meta.core.bean.CrawlerMetaConstant;
import com.chance.cc.crawler.meta.core.bean.job.CrawlerScheduleJob;
import com.chance.cc.crawler.prod.command.job.domain.commerce.amazon.AmazonCommonScript;
import org.apache.commons.lang3.StringUtils;

import static com.chance.cc.crawler.core.CrawlerEnum.CrawlerRequestType.*;

/**
 * created by CC on 2020/11/26
 * mail 279020185@qq.com
 */
public class AmazonCrawlerScheduleJob extends AmazonCommonScript {//-
    public static String site = "commodity";//站点-
    public static void main(String[] args) {
        publishCrawlerScheduleJobInfo();
    }//-

    public static CrawlerJob publishCrawlerScheduleJobInfo(){//发布-
        CrawlerJob crawlerJob = amazonScheduler();//采集-

        //发布定时采集作业
        CrawlerScheduleJob crawlerScheduleJob = new CrawlerScheduleJob();//定时采集作业
        crawlerScheduleJob.setDomain(domain);//设置域
        crawlerScheduleJob.setCrawlerJob(JSON.toJSONString(crawlerJob));//设置采集信息
        crawlerScheduleJob.setJobType(CrawlerMetaConstant.ScheduleCrawlerJobType.crawler.enumVal());//工作标签
        crawlerScheduleJob.setNote("亚马逊文章1点定时采集");//采集提示-
        crawlerScheduleJob.setCrawlerKey(crawlerJob.generateCrawlerKey());//生成爬虫key
        HttpPage page = metaServiceCommand.addOrUpdateCrawlerScheduleJob(crawlerScheduleJob);//发布标签命令添加或修改脚本调度工作
        System.out.println("发布作业：" + page.getRawText());//打印文本
        return crawlerJob;//返回工作爬虫
    }

    /**
     * taobao采集
     * @return
     */
    public static CrawlerJob amazonScheduler() {//调度-
        String url = "https://www.amazon.cn";//-
        String site_biz = "article";//-
        HttpConfig httpConfig = HttpConfig.me(domain);//配置domain
        httpConfig.setHttpSite(site);//配置site

        CrawlerRequestRecord crawlerRequestRecord = CrawlerRequestRecord.builder()
                .startPageRequest(domain, CrawlerEnum.CrawlerRequestType.turnPage)
                .httpConfig(httpConfig)//-
                .domain(domain)
                .httpUrl(url)
                .recordKey(url)
                .releaseTime(System.currentTimeMillis())
//                .filter(CrawlerEnum.CrawlerRecordFilter.keyOrDateRange)
//                .addFilterInfo(FilterUtils.redisFilterKeyInfo(StringUtils.joinWith("-","filter",domain,site,site_biz,"queue")))//根据redis中的值去重（不是本地）-
                .filter(CrawlerEnum.CrawlerRecordFilter.dateRange)
                .addFilterInfo(FilterUtils.dateRangeFilterInfo(25,null))
                .proxy(proxy)
                .resultLabelTag(CrawlerEnum.CrawlerDataType.article)
                .httpHead("Connection","keep-alive")
                .httpHead("Cache-Control","max-age=0")
                .httpHead("rtt","100")
                .httpHead("downlink","10")
                .httpHead("ect","4g")
                .httpHead("sec-ch-ua","\"Google Chrome\";v=\"93\", \" Not;A Brand\";v=\"99\", \"Chromium\";v=\"93\"")
                .httpHead("sec-ch-ua-mobile","?0")
                .httpHead("Upgrade-Insecure-Requests","1")
                .httpHead("User-Agent",getRandomUA())
                .httpHead("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9")
                .httpHead("Sec-Fetch-Site","same-origin")
                .httpHead("Sec-Fetch-User","?1")
                .httpHead("Sec-Fetch-Dest","document")
                .httpHead("Accept-Language","zh-CN,zh;q=0.9")
                .httpHead("Cookie","session-id=462-8168812-7024355; i18n-prefs=CNY; lc-acbcn=zh_CN; ubid-acbcn=460-7097111-9030419; session-token=ugupkmxReZDKiKU9dL2bTGGOPx7wT4YHSOqf8ABSKwOEdq0RIJRHKMf4phDM7NatJN8aKJR16euN4hvm/azrL/N0PpnggNhDcOs51w65DOCWe2SNI9Li/NwcPUe6lzCxB6U76vQRSCWSWGtFaPSqeUiBGWOfULVJ6Hi0qYFfXpVn61b1Ne6k4q8Ez/wi4uy7; session-id-time=2082787201l; csm-hit=tb:X1YHY8ZT6ANH2MPSB6AF+s-HHNT7Y9CTWD0RJF70XG5|1634023110426&t:1634023110427&adb:adblk_no")
                .build();
        crawlerRequestRecord.tagsCreator().bizTags().addDomain(domain);
        crawlerRequestRecord.tagsCreator().bizTags().addSite(site);
        crawlerRequestRecord.tagsCreator().bizTags().addSiteBiz(site_biz);//-

        //添加评论去重信息
        CrawlerRecord filterCrawlerRecord = new CrawlerRecord();//过滤爬虫记录
        filterCrawlerRecord.setFilter(CrawlerEnum.CrawlerRecordFilter.keyOrDateRange);//根据key和时间过滤
        filterCrawlerRecord.addFilterInfo(FilterUtils.memoryFilterKeyInfo(StringUtils.joinWith("-", filter, domain, "comment")));//内存过滤
        filterCrawlerRecord.addFilterInfo(FilterUtils.dateRangeFilterInfo(24*7, null));//时间范围过滤
        crawlerRequestRecord.tagsCreator().bizTags().addCustomKV("comment_record_filter_info", JSON.toJSONString(filterCrawlerRecord));//自定义标签


        //请求队列名
        String requestQueueName = StringUtils.joinWith("-","crawler",domain,site,site_biz,"queue");//请求队列名

        //车系关键字
        CrawlerRequestRecord initNewsCrawlerRecord = CrawlerRequestRecord.builder()
                .startPageRequest("amazon_series_keywords",turnPageItem)//-
                .httpUrl(metaServiceHttpPrefix+"/v1/meta/"+domain+"/keys?site="+site)//-
                .requestLabelTag(supportSource)
                .requestLabelTag(internalDownload)
                .build();

        //配置结果队列信息
        String resultQueueName ="crawler_result_queue_Amazon_Commodity_"+site_biz;
        CrawlerQueueConfig crawlerQueueConfig = new CrawlerQueueConfig(//爬虫队列配置
                resultQueueName,
                CrawlerQueueConfig.Content.result,//放到结果集中
                CrawlerQueueConfig.Storage.redis,//放到redis中
                CrawlerQueueConfig.Structure.list);//list结构

        //同步到mysql callback record
        CrawlerRequestRecord syncCrawlerRecord = CrawlerRequestRecord.builder()
                .startPageRequest(domain+"_"+site+"_sync", turnPageItem)
                .httpUrl(metaServiceHttpPrefix + "/crawler/domain/common/api/v1/"+domain+"/search/results/sync?resultQueue=" +resultQueueName + "&site=" + site_biz)
                .requestLabelTag(supportCallback)
                .requestLabelTag(internalDownload)
                .build();

        CrawlerJob crawlerJob = CrawlerJob.builder()
                .crawlerJobThreadNumber(10)//十个线程
                .triggerInfo(
                        domain,
                        CrawlerMetaConstant.ScheduleJobTrigger_Cron,
                        System.currentTimeMillis(),
                        StringUtils.joinWith("-", domain, site,site_biz, CrawlerMetaConstant.ScheduleJobTrigger_Cron))
                .crawlerRequestQueue(CrawlerMetaConstant.redisRequestQueue(requestQueueName))//请求队列
                .queueResultPipeline("redis",crawlerQueueConfig)//链接保存在redis中-
                .kafkaResultPipeline("kafka",kafkaTopic, null)//数据保存在kafka中-
                .requestRecord(crawlerRequestRecord)
                .supportRecord(syncCrawlerRecord)
                .supportRecord(initNewsCrawlerRecord)
                .build();
        return crawlerJob;
    }

}
